import React, { useState, useEffect, useCallback } from 'react'
import { Layout, Row, Col, Card, message } from 'antd'
import { useAppSelector, useAppDispatch } from '@/store'
import MonacoSQLEditor from '@/components/Editor/MonacoSQLEditor'
import ExecutionPanel, { ExecutionOptions } from './ExecutionPanel'
import ExecutionProgress, { ExecutionStatus } from './ExecutionProgress'
import ExecutionResultTable, { ExecutionResult } from './ExecutionResultTable'
import ExecutionHistory, { ExecutionHistoryItem } from './ExecutionHistory'
import { Connection } from '@/types/connection'
import * as executionAPI from '@/services/executionAPI'

const { Content, Sider } = Layout

interface SQLExecutorProps {
  initialSQL?: string
  initialConnection?: Connection | null
  onSQLChange?: (sql: string) => void
  onConnectionChange?: (connection: Connection | null) => void
  showHistory?: boolean
  showProgress?: boolean
  height?: number
}

const SQLExecutor: React.FC<SQLExecutorProps> = ({
  initialSQL = '',
  initialConnection = null,
  onSQLChange,
  onConnectionChange,
  showHistory = true,
  showProgress = true,
  height = 600,
}) => {
  const dispatch = useAppDispatch()
  const { connections } = useAppSelector(state => state.connection)
  const { theme } = useAppSelector(state => state.ui)
  
  // 状态管理
  const [sql, setSQL] = useState(initialSQL)
  const [selectedConnection, setSelectedConnection] = useState<Connection | null>(initialConnection)
  const [execution, setExecution] = useState<ExecutionStatus | null>(null)
  const [result, setResult] = useState<ExecutionResult | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [history, setHistory] = useState<ExecutionHistoryItem[]>([])
  const [historyLoading, setHistoryLoading] = useState(false)
  const [siderCollapsed, setSiderCollapsed] = useState(false)

  // 加载执行历史
  const loadHistory = useCallback(async () => {
    try {
      setHistoryLoading(true)
      const response = await executionAPI.getExecutionHistory({
        limit: 50,
        offset: 0,
      })
      if (response.success && response.data) {
        setHistory(response.data.executions)
      }
    } catch (error) {
      console.error('加载执行历史失败:', error)
    } finally {
      setHistoryLoading(false)
    }
  }, [])

  // 处理SQL变化
  const handleSQLChange = (newSQL: string) => {
    setSQL(newSQL)
    onSQLChange?.(newSQL)
  }

  // 处理连接变化
  const handleConnectionChange = (connectionId: string) => {
    const connection = connections.find(c => c.id === connectionId) || null
    setSelectedConnection(connection)
    onConnectionChange?.(connection)
  }

  // 处理SQL执行
  const handleExecute = async (options: ExecutionOptions) => {
    if (!selectedConnection) {
      message.error('请选择数据库连接')
      return
    }

    try {
      // 重置状态
      setResult(null)
      setError(null)
      
      // 设置执行状态
      const executionId = `exec_${Date.now()}`
      setExecution({
        id: executionId,
        status: 'running',
        start_time: new Date().toISOString(),
        message: '正在执行SQL查询...',
        stages: [
          { name: '连接数据库', status: 'completed', duration: 100 },
          { name: '解析SQL语句', status: 'completed', duration: 50 },
          { name: '执行查询', status: 'running' },
        ],
      })

      // 调用执行API
      const response = await executionAPI.executeSQL({
        connection_id: options.connectionId,
        sql: options.sql,
        limit: options.limit,
        timeout: options.timeout,
        auto_commit: options.autoCommit,
        explain_only: options.explainOnly,
      })

      if (response.success && response.data) {
        // 执行成功
        setExecution({
          id: executionId,
          status: 'completed',
          start_time: execution?.start_time || new Date().toISOString(),
          end_time: new Date().toISOString(),
          duration: response.data.execution_time,
          message: '查询执行完成',
          stages: [
            { name: '连接数据库', status: 'completed', duration: 100 },
            { name: '解析SQL语句', status: 'completed', duration: 50 },
            { name: '执行查询', status: 'completed', duration: response.data.execution_time - 150 },
          ],
        })

        setResult({
          columns: response.data.columns,
          rows: response.data.rows,
          total_rows: response.data.total_rows,
          affected_rows: response.data.affected_rows,
          execution_time: response.data.execution_time,
          query_id: response.data.query_id,
        })

        message.success(`查询执行完成，返回 ${response.data.total_rows} 行数据`)
      } else {
        throw new Error(response.error?.message || '执行失败')
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '未知错误'
      
      setExecution({
        id: execution?.id || `exec_${Date.now()}`,
        status: 'failed',
        start_time: execution?.start_time || new Date().toISOString(),
        end_time: new Date().toISOString(),
        error: errorMessage,
        message: '查询执行失败',
      })

      setError(errorMessage)
      message.error(`执行失败: ${errorMessage}`)
    } finally {
      // 刷新历史记录
      loadHistory()
    }
  }

  // 处理取消执行
  const handleCancel = async () => {
    if (!execution || execution.status !== 'running') {
      return
    }

    try {
      await executionAPI.cancelExecution(execution.id)
      
      setExecution({
        ...execution,
        status: 'cancelled',
        end_time: new Date().toISOString(),
        message: '查询已取消',
      })

      message.info('查询已取消')
    } catch (error) {
      message.error('取消执行失败')
    }
  }

  // 处理重试执行
  const handleRetry = () => {
    if (!selectedConnection) return

    const options: ExecutionOptions = {
      connectionId: selectedConnection.id,
      sql,
      limit: 1000,
      timeout: 30000,
      autoCommit: true,
      explainOnly: false,
    }

    handleExecute(options)
  }

  // 处理历史记录重新执行
  const handleHistoryExecute = (historySql: string, connectionId: string) => {
    const connection = connections.find(c => c.id === connectionId)
    if (!connection) {
      message.error('连接不存在')
      return
    }

    setSQL(historySql)
    setSelectedConnection(connection)
    
    const options: ExecutionOptions = {
      connectionId,
      sql: historySql,
      limit: 1000,
      timeout: 30000,
      autoCommit: true,
      explainOnly: false,
    }

    handleExecute(options)
  }

  // 处理历史记录删除
  const handleHistoryDelete = async (id: string) => {
    try {
      await executionAPI.deleteExecutionHistory(id)
      setHistory(history.filter(item => item.id !== id))
      message.success('删除成功')
    } catch (error) {
      message.error('删除失败')
    }
  }

  // 处理清空历史
  const handleHistoryClear = async () => {
    try {
      await executionAPI.clearExecutionHistory()
      setHistory([])
      message.success('历史记录已清空')
    } catch (error) {
      message.error('清空失败')
    }
  }

  // 处理结果导出
  const handleExport = async (format: 'csv' | 'excel' | 'json') => {
    if (!result || !execution) {
      message.warning('没有可导出的数据')
      return
    }

    try {
      const blob = await executionAPI.exportExecutionResult(execution.id, format)
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `query_result_${Date.now()}.${format}`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      
      message.success('导出成功')
    } catch (error) {
      message.error('导出失败')
    }
  }

  // 初始化
  useEffect(() => {
    if (showHistory) {
      loadHistory()
    }
  }, [showHistory, loadHistory])

  const siderWidth = siderCollapsed ? 0 : 320

  return (
    <Layout style={{ height, background: 'transparent' }}>
      {/* 主内容区域 */}
      <Content style={{ display: 'flex', flexDirection: 'column' }}>
        {/* SQL编辑器 */}
        <Card 
          size="small" 
          style={{ marginBottom: 16 }}
          bodyStyle={{ padding: 0 }}
        >
          <MonacoSQLEditor
            value={sql}
            onChange={handleSQLChange}
            height={200}
            connectionId={selectedConnection?.id}
            enableSchemaIntelliSense={true}
          />
        </Card>

        {/* 执行控制面板 */}
        <ExecutionPanel
          sql={sql}
          selectedConnection={selectedConnection}
          execution={execution}
          onExecute={handleExecute}
          onCancel={handleCancel}
          onConnectionChange={handleConnectionChange}
        />

        {/* 执行进度 */}
        {showProgress && execution && (
          <ExecutionProgress
            execution={execution}
            onCancel={handleCancel}
            onRetry={handleRetry}
            showStages={true}
          />
        )}

        {/* 执行结果 */}
        <div style={{ flex: 1, minHeight: 0 }}>
          <ExecutionResultTable
            result={result}
            loading={execution?.status === 'running'}
            error={error}
            onExport={handleExport}
            maxHeight={height - 400}
          />
        </div>
      </Content>

      {/* 右侧历史面板 */}
      {showHistory && (
        <Sider
          width={320}
          collapsible
          collapsed={siderCollapsed}
          onCollapse={setSiderCollapsed}
          collapsedWidth={0}
          style={{
            background: theme === 'dark' ? '#1f1f1f' : '#fff',
            borderLeft: '1px solid #f0f0f0',
            marginLeft: 16,
          }}
        >
          <div style={{ height: '100%', padding: 16 }}>
            <ExecutionHistory
              history={history}
              loading={historyLoading}
              onExecute={handleHistoryExecute}
              onDelete={handleHistoryDelete}
              onClear={handleHistoryClear}
              maxHeight={height - 100}
            />
          </div>
        </Sider>
      )}
    </Layout>
  )
}

export default SQLExecutor